﻿#if NETCOREAPP3_0
using Longbow.ComponentModel;
using System;
using System.Collections;
using System.IO;
using System.Reflection;

namespace Bootstrap.Security.Mvc
{
    public static class TestHelper
    {
        private readonly static object _fileLocker = new object();

        public static void AuthorizateLicense(Type type)
        {
            var licenseProvider = typeof(LgbLicenseProvider);
            var collection = licenseProvider.GetField("LicenseCollector", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null) as IDictionary;

            // 构造LgbLicenseType枚举
            var t = new LgbLicenseProvider();
            var licenseType = t.GetType().Assembly.GetType("Longbow.ComponentModel.LgbLicenseType");
            var licenseTypInstance = Activator.CreateInstance(licenseType);
            licenseTypInstance = Enum.Parse(licenseType, "Expiration");

            // 构造LgbLicense
            var lgbLicense = t.GetType().Assembly.GetType("Longbow.ComponentModel.LgbLicense");
            var lgbLicenseInstance = Activator.CreateInstance(lgbLicense, new object[] { licenseTypInstance, DateTime.Now.AddMinutes(10).ToString() });

            collection.Remove(type);
            collection.Add(type, lgbLicenseInstance);
        }

        public static void ClearLicenseCache(Action<string> callback)
        {
            // LicenseCollector
            var licenseProvider = typeof(LgbLicenseProvider);
            var collection = licenseProvider.GetField("LicenseCollector", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null) as IDictionary;
            collection.Clear();

            var lic = Path.Combine(AppContext.BaseDirectory, "Longbow.Lic");
            lock (_fileLocker)
            {
                if (File.Exists(lic)) File.Delete(lic);
                callback(lic);
            }
        }
    }
}
#endif
